import tkinter as tk
from tkinter import messagebox, ttk
import redis
import ast
import utils

class EmployeeManagement:
    def __init__(self, parent):
        self.parent = parent
        self.create_widgets()
        self.load_employees()

    def create_widgets(self):
        self.frame = tk.Frame(self.parent)
        self.frame.pack(fill=tk.BOTH, expand=True)

        # Main Treeview with Scrollbars
        self.tree_frame = tk.Frame(self.frame)
        self.tree_frame.pack(fill=tk.BOTH, expand=True)

        self.tree_scrollbar_y = tk.Scrollbar(self.tree_frame, orient=tk.VERTICAL)
        self.tree_scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)

        self.tree_scrollbar_x = tk.Scrollbar(self.tree_frame, orient=tk.HORIZONTAL)
        self.tree_scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)

        self.tree = ttk.Treeview(self.tree_frame, columns=("Eid", "EName", "EPas", "Elevel", "EtelPhone", "ESalary", "other"), 
                                 show='headings', yscrollcommand=self.tree_scrollbar_y.set, xscrollcommand=self.tree_scrollbar_x.set)
        self.tree.heading("Eid", text="Employee ID")
        self.tree.heading("EName", text="Name")
        self.tree.heading("EPas", text="Password")
        self.tree.heading("Elevel", text="Level")
        self.tree.heading("EtelPhone", text="Phone")
        self.tree.heading("ESalary", text="Salary")
        self.tree.heading("other", text="Remarks")
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree_scrollbar_y.config(command=self.tree.yview)
        self.tree_scrollbar_x.config(command=self.tree.xview)

        self.tree.bind("<<TreeviewSelect>>", self.on_tree_select)

        self.button_frame = tk.Frame(self.parent)
        self.button_frame.pack(fill=tk.X)

        self.add_button = tk.Button(self.button_frame, text="Add Employee", command=self.add_employee)
        self.add_button.pack(side=tk.LEFT, padx=5, pady=5)

        self.update_button = tk.Button(self.button_frame, text="Update Employee", command=self.update_employee)
        self.update_button.pack(side=tk.LEFT, padx=5, pady=5)

        self.delete_button = tk.Button(self.button_frame, text="Delete Employee", command=self.delete_employee)
        self.delete_button.pack(side=tk.LEFT, padx=5, pady=5)

        self.export_button = tk.Button(self.button_frame, text="Export to CSV", command=self.export_employees)
        self.export_button.pack(side=tk.LEFT, padx=5, pady=5)

    def load_employees(self):
        self.tree.delete(*self.tree.get_children())
        r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
        employees = r.hgetall('tb_employee')
        for eid, employee in employees.items():
            employee_data = ast.literal_eval(employee)
            self.tree.insert("", "end", values=(
                eid, 
                employee_data.get('EName', 'N/A'), 
                employee_data.get('EPas', 'N/A'), 
                employee_data.get('Elevel', 'N/A'), 
                employee_data.get('EtelPhone', 'N/A'), 
                employee_data.get('ESalary', 'N/A'), 
                employee_data.get('other', '')
            ))

    def on_tree_select(self, event):
        selected_items = self.tree.selection()
        if selected_items:
            selected_item = selected_items[0]
            self.selected_employee = self.tree.item(selected_item, "values")
        else:
            self.selected_employee = None

    def add_employee(self):
        self.employee_popup("Add Employee", self.save_new_employee)

    def update_employee(self):
        if hasattr(self, 'selected_employee') and self.selected_employee:
            self.employee_popup("Update Employee", self.save_updated_employee, self.selected_employee)
        else:
            messagebox.showwarning("Warning", "Please select an employee first")

    def delete_employee(self):
        if hasattr(self, 'selected_employee') and self.selected_employee:
            r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
            r.hdel('tb_employee', self.selected_employee[0])
            self.load_employees()
        else:
            messagebox.showwarning("Warning", "Please select an employee first")

    def export_employees(self):
        r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
        employees = r.hgetall('tb_employee')
        utils.export_to_csv(employees, 'employees.csv')

    def employee_popup(self, title, save_command, employee_data=None):
        print(f"Opening popup: {title}")
        popup = tk.Toplevel(self.parent)
        popup.title(title)
        popup.geometry("600x600")  # Increased window size

        fields = ["Eid", "EName", "EPas", "Elevel", "EtelPhone", "ESalary", "other"]
        entries = {}

        for field in fields:
            print(f"Creating label and entry for field: {field}")
            label = tk.Label(popup, text=field.replace('_', ' ').title())
            label.pack(pady=5)
            entry = tk.Entry(popup)
            entry.pack(pady=5)
            entries[field] = entry

        if employee_data:
            print(f"Populating popup with existing data: {employee_data}")
            for i, field in enumerate(fields):
                entries[field].insert(0, employee_data[i])
                if field == "Eid":
                    entries[field].config(state='readonly')  # Make the ID field read-only
        else:
            print("Creating new entry fields")
            # Generate new ID for new entry
            new_eid = self.generate_id('Eid')
            print(f"Generated new Employee ID: {new_eid}")
            entries["Eid"].insert(0, new_eid)
            entries["Eid"].config(state='readonly')  # Make the ID field read-only

        save_button = tk.Button(popup, text="Save", command=lambda: save_command(entries, popup))
        save_button.pack(pady=20)
        print("Popup creation complete")

    def save_new_employee(self, entries, popup):
        try:
            employee_data = {field: entry.get() for field, entry in entries.items()}
            print(f"Saving new employee data: {employee_data}")  # Debug statement
            r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
            r.hset('tb_employee', employee_data['Eid'], str(employee_data))
            self.load_employees()
            popup.destroy()
        except Exception as e:
            print(f"Error saving new employee: {e}")
            messagebox.showerror("Error", f"Unable to save employee: {e}")

    def save_updated_employee(self, entries, popup):
        try:
            employee_data = {field: entry.get() for field, entry in entries.items()}
            print(f"Saving updated employee data: {employee_data}")  # Debug statement
            r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
            r.hset('tb_employee', employee_data['Eid'], str(employee_data))
            self.load_employees()
            popup.destroy()
        except Exception as e:
            print(f"Error saving updated employee: {e}")
            messagebox.showerror("Error", f"Unable to update employee: {e}")

    def generate_id(self, prefix):
        r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
        current_id = r.incr('Eid_counter', 1) + 9999  # 从10000开始
        eid = f"yg{current_id:05d}"
        return eid

if __name__ == "__main__":
    root = tk.Tk()
    app = EmployeeManagement(root)
    root.mainloop()
